package com.lld.im.service.message.mq;

import com.alibaba.fastjson.JSONObject;
import com.lld.im.common.constants.Constants;
import com.lld.im.common.enums.commond.GroupEventCommand;
import com.lld.im.common.enums.commond.MessageCommand;
import com.lld.im.common.model.message.GroupMessageContent;
import com.lld.im.common.model.message.MessageContent;
import com.lld.im.service.message.server.P2PMessageServer;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ReactiveStreamCommands;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class MqChartMsgReceiver {

    @Autowired
   private P2PMessageServer p2PMessageServer;


    /**
     * durable 是否持久化
     * concurrency 并发消费者的数量为1，表示同时只有一个消费者处理消息
     * Channel: 当前与mq的连接通道 用来进行ack确认
     *
     * 在tcp层已经完成了对交换机以及队列的初始化 这里就不基于注解实现bind了
     */
//    @RabbitListener(
//            bindings = @QueueBinding(
//                    value = @Queue(value = Constants.RabbitConstants.Im2MessageService, durable = "true"),
//                    exchange = @Exchange(value = Constants.RabbitConstants.Im2MessageService)
//            ),concurrency = "1"
//    )
    @RabbitListener(queues = Constants.RabbitConstants.Im2MessageService)
    public void onReceiverChart(@Payload  Message message,
                            @Headers  Map<String,Object> headers, Channel channel) throws Exception {
        //dataStr : 包含一个command dataStr
        String dataStr = new String(message.getBody(), "utf-8");
        log.info("im-server 收到mq消息 ==={}", dataStr);
        JSONObject jsonObject = JSONObject.parseObject(dataStr);
        //根据不同命令 来实现消息的不同投递
        Integer command = jsonObject.getInteger("command");
        //TODO 接收消息前 需要判断用户是否被禁言/账号是否禁用 双方的好友关系
        if (command == MessageCommand.MSG_P2P.getCommand()) {
            MessageContent messageContent = jsonObject.toJavaObject(MessageContent.class);
            p2PMessageServer.process(messageContent);
        }
    }
}
